import React, { useEffect, useState } from "react";
import { Button, ErrorBlock, Form, Input, List, Modal, Popup, Steps, TextArea, Toast } from "antd-mobile";
import { AddOutline, CheckCircleFill, CloseCircleFill, } from "antd-mobile-icons";
import "./index.scss";
import { useNavigate, useBlocker } from "react-router-dom";
import { sendEmail, publicUpload } from "@/api/modules/case";
import useStore from "@/store";
import { t } from "@/lang";

const CaseMain: React.FC = () => {
  const [fileList, setFileList] = useState<string[]>([]);
  const [current, setCurrent] = useState(0);
  const [milVisible, setMilVisible] = useState(false);
  const [medVisible, setMedVisible] = useState(false);
  const [form] = Form.useForm();
  const [userForm] = Form.useForm();
  const [infoForm] = Form.useForm();
  const [sendForm] = Form.useForm();
  const { caseStudyForm, designCaseStudyForm } = useStore();
  const [initialValues] = useState(caseStudyForm);
  const navigate = useNavigate();

  useBlocker((re) => {
    designCaseStudyForm(form.getFieldsValue());
    return false;
  });

  const handleFileUpload = async (file: File) => {
    const formData = new FormData() as any;
    formData.append("files", file);
    formData.append("type", "3");
    const { data } = await publicUpload(formData);
    setFileList((pre) => [...pre, data.url]);
  };

  const getIcon = (status: number) => {
    if (current > status) {
      return <CheckCircleFill color="#b52121" />;
    } else if (current < status) {
      return <div className="process_icon"></div>;
    } else {
      return (
        <div className="wait_icon">
          <div className="inner"></div>
        </div>
      );
    }
  };
  const setMile = (mile: string) => {
    form.setFieldValue("mileage_units", mile);
    form.validateFields(["mileage_units"]);
    setMilVisible(false);
  };
  const setMed = (med: string) => {
    userForm.setFieldValue("contact_method", med);
    userForm.validateFields(["contact_method"]);
    setMedVisible(false);
  };
  const handleFinished = () => {
    designCaseStudyForm(form.getFieldsValue());
    setCurrent(current + 1);
    console.log("你好", form.getFieldsValue());
  };
  const handleFailed = (e: any) => {
    Toast.show(e.errorFields[0].errors[0]);
  };
  const handleUserFinished = () => {
    designCaseStudyForm(userForm.getFieldsValue());
    setCurrent(current + 1);
  };
  const handleInfoFinished = () => {
    infoForm.setFieldValue("attachments", fileList.join(","));
    designCaseStudyForm(infoForm.getFieldsValue());
    setCurrent(current + 1);
  };
  const handleSendFinished = () => {
    designCaseStudyForm(sendForm.getFieldsValue());
    sendEmail(caseStudyForm).then(res => {
      if (res.code === 0) {
        setCurrent(current + 1);
      } else {
        Toast.show(res.message!);
      }
    });
  };
  const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectFiles = e.target.files;
    if (!selectFiles) return;
    console.log(selectFiles);
    const numMax = 9 - fileList.length;
    Array.from(selectFiles)
      .slice(0, numMax)
      .forEach((element) => {
        if (element.type.includes("image") || element.type.includes("video")) {
          handleFileUpload(element);
        } else {
          Toast.show(t("case.t_1"));
        }
      });
  };
  const deleteFile = (index: number) => {
    const copyFileList = [...fileList];
    copyFileList.splice(index, 1);
    setFileList(copyFileList);
  };
  return (
    <div id="case_main">
      <header>{t("case.t_2")}</header>

      <Steps current={current}>
        <Steps.Step title={t('case.t_34')} icon={getIcon(0)} />
        <Steps.Step title={t('case.t_35')} icon={getIcon(1)} />
        <Steps.Step title={t('case.t_36')} icon={getIcon(2)} />
        <Steps.Step title={t('case.t_37')} icon={getIcon(3)} />
        <Steps.Step title={t('case.t_38')} icon={getIcon(4)} />
      </Steps>

      {current === 0 && (
        <Form
          onFinishFailed={handleFailed}
          onFinish={handleFinished}
          mode="card"
          form={form}
          initialValues={initialValues}
        >
          <div className="form_item">
            <div className="title">
              {t('case.t_3')}<span>*</span>
            </div>
            <Form.Item
              name="brand"
              rules={[{ required: true, message: t("case.t_4", { aa: t('case.t_3') }) }]}
              onClick={() => navigate(`/case/search/1`)}
              arrow
            >
              <Input placeholder={t('case.t_4', { aa: t("case.t_3") })} readOnly />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_5')}<span>*</span>
            </div>
            <Form.Item
              name="model"
              rules={[{ required: true, message: t('case.t_4', { aa: t("case.t_5") }) }]}
              onClick={() =>
                initialValues.brand
                  ? navigate(`/case/search/2`)
                  : Toast.show(t('case.t_4', { aa: t("case.t_5") }))
              }
              arrow
            >
              <Input placeholder={t('case.t_4', { aa: t("case.t_5") })} readOnly />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_6')}<span>*</span>
            </div>
            <Form.Item
              name="vin_number"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_6") }) }]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_6") })} clearable />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_7')}<span>*</span>
            </div>
            <Form.Item
              name="year"
              rules={[{ required: true, message: t('case.t_4', { aa: t("case.t_7") }) }]}
              onClick={() =>
                initialValues.model
                  ? navigate(`/case/search/3`)
                  : Toast.show("Select model")
              }
              arrow
            >
              <Input placeholder={t('case.t_4', { aa: t("case.t_7") })} readOnly />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_8')}<span>*</span>
            </div>
            <Form.Item
              name="mileage"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_8") }) }]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_8") })} clearable />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_9')}
              <span>*</span>
            </div>
            <Form.Item
              name="mileage_units"
              rules={[{ required: true, message: t('case.t_4', { aa: t("case.t_9") }) }]}
              onClick={() => setMilVisible(true)}
              arrow
            >
              <Input placeholder={t('case.t_4', { aa: t("case.t_9") })} readOnly />
            </Form.Item>
          </div>
          <div className="bottom_btn">
            <Button fill="none" color="primary" type="submit">
              {t('case.t_10')}
            </Button>
          </div>
        </Form>
      )}
      {current === 1 && (
        <Form
          onFinishFailed={handleFailed}
          onFinish={handleUserFinished}
          mode="card"
          form={userForm}
          initialValues={initialValues}
        >
          <div className="form_item">
            <div className="title">
              {t('case.t_11')}<span>*</span>
            </div>
            <Form.Item
              name="serial_number"
              rules={[
                { required: true, message: t('case.t_14', { aa: t("case.t_11") }) },
              ]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_11") })} clearable />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_12')}<span>*</span>
            </div>
            <Form.Item
              name="contact_name"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_12") }) }]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_12") })} clearable />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_13')}<span>*</span>
            </div>
            <Form.Item
              name="contact_phone"
              rules={[
                { required: true, message: t('case.t_14', { aa: t("case.t_13") }) },
              ]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_13") })} clearable />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_15')}
              <span>*</span>
            </div>
            <Form.Item
              name="contact_email"
              rules={[
                { required: true, message: t('case.t_14', { aa: t("case.t_15") }) },
              ]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_15") })} clearable />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_16')}
              <span>*</span>
            </div>
            <Form.Item
              name="contact_method"
              rules={[{ required: true, message: t('case.t_4', { aa: t("case.t_16 ") }) }]}
              onClick={() => setMedVisible(true)}
              arrow
            >
              <Input placeholder={t('case.t_4', { aa: t("case.t_16") })} readOnly />
            </Form.Item>
          </div>
          <div className="bottom_btn">
            <Button
              fill="none"
              color="primary"
              onClick={() => setCurrent(current - 1)}
            >
              {t('case.t_17')}
            </Button>
            <Button fill="none" color="primary" type="submit">
              {t('case.t_10')}
            </Button>
          </div>
        </Form>
      )}
      {current === 2 && (
        <Form
          onFinishFailed={handleFailed}
          onFinish={handleInfoFinished}
          mode="card"
          form={infoForm}
          initialValues={initialValues}
        >
          <div className="form_item">
            <div className="title">
              {t('case.t_18')}<span>*</span>
            </div>
            <Form.Item
              name="symptoms"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_18") }) }]}
            >
              <TextArea
                showCount
                maxLength={1000}
                placeholder={t('case.t_14', { aa: t("case.t_18") })}
                autoSize={{ minRows: 3, maxRows: 5 }}
              />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_19')}<span>*</span>
            </div>
            <Form.Item
              name="work_done"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_19") }) }]}
            >
              <TextArea
                showCount
                maxLength={1000}
                placeholder={t('case.t_14', { aa: t("case.t_19") })}
                autoSize={{ minRows: 3, maxRows: 5 }}
              />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_20')}<span>*</span>
            </div>
            <Form.Item
              name="faults"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_20") }) }]}
            >
              <TextArea
                showCount
                maxLength={1000}
                placeholder={t('case.t_14', { aa: t("case.t_20") })}
                autoSize={{ minRows: 3, maxRows: 5 }}
              />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_21')}<span>*</span>
            </div>
            <Form.Item
              name="additional_information"
              rules={[
                {
                  required: true,
                  message: t('case.t_14', { aa: t("case.t_21") }),
                },
              ]}
            >
              <TextArea
                showCount
                maxLength={1000}
                placeholder={t('case.t_14', { aa: t("case.t_21") })}
                autoSize={{ minRows: 3, maxRows: 5 }}
              />
            </Form.Item>
          </div>
          <div className="form_item">
            <div className="title">
              {t('case.t_22')}<span>*</span><span className="file_num">({fileList.length}/9)</span>
            </div>
            <Form.Item
              name="attachments"
              rules={[
                {
                  required: true,
                  message: t('case.t_14', { aa: t("case.t_22") }),
                },
              ]}
            >
              <div className="upload_area flex-start">
                {fileList.map((url, index) => (
                  <div key={index} className="preview_item flex-center">
                    {url.endsWith("mp4") ? (
                      <video
                        src={url}
                        onClick={() =>
                          Modal.show({
                            content: <video src={url} controls autoPlay />,
                            bodyClassName: "case_video_dialog",
                            showCloseButton: true,
                          })
                        }
                      ></video>
                    ) : (
                      <img object-fit="contain" src={url} />
                    )}
                    <CloseCircleFill
                      fontSize={18}
                      onClick={() => deleteFile(index)}
                    />
                  </div>
                ))}
                {fileList.length < 9 && (
                  <div className="upload_wrapper flex-center">
                    <AddOutline fontSize={30} color="#cccccc" />
                    <input type="file" multiple onChange={handleUpload} />
                  </div>
                )}
              </div>
            </Form.Item>
          </div>
          <div className="bottom_btn">
            <Button
              fill="none"
              color="primary"
              onClick={() => setCurrent(current - 1)}
            >
              {t('case.t_17')}
            </Button>
            <Button fill="none" color="primary" type="submit">
              {t('case.t_10')}
            </Button>
          </div>
        </Form>
      )}
      {current === 3 && (
        <Form
          onFinishFailed={handleFailed}
          onFinish={handleSendFinished}
          mode="card"
          form={sendForm}
          initialValues={initialValues}
        >
          <div className="form_item">
            <div className="title">
              {t('case.t_23')}<span>*</span>
            </div>
            <Form.Item
              name="to_email"
              rules={[{ required: true, message: t('case.t_14', { aa: t("case.t_25") }) }, { pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: t('case.t_24') }]}
            >
              <Input placeholder={t('case.t_14', { aa: t("case.t_25") })} clearable />
            </Form.Item>
          </div>
          <div className="bottom_btn">
            <Button
              fill="none"
              color="primary"
              onClick={() => setCurrent(current - 1)}
            >
              {t('case.t_17')}
            </Button>
            <Button fill="none" color="primary" type="submit">
              {t('case.t_26')}
            </Button>
          </div>
        </Form>
      )}
      {current === 4 && <ErrorBlock
        status="empty"
        image={
          <CheckCircleFill fontSize={90} color="#32cf78" />
        }
        description={t('case.t_27, { aa: caseStudyForm.to_email }')}
      />}

      <Popup
        visible={milVisible}
        showCloseButton
        onClose={() => {
          setMilVisible(false);
        }}
      >
        <List header={t('case.t_32')}>
          <List.Item onClick={() => setMile(t('case.t_28'))}>{t('case.t_28')}</List.Item>
          <List.Item onClick={() => setMile(t('case.t_29'))}>{t('case.t_29')}</List.Item>
        </List>
      </Popup>
      <Popup
        visible={medVisible}
        showCloseButton
        onClose={() => {
          setMedVisible(false);
        }}
      >
        <List header={t('case.t_30')}>
          <List.Item onClick={() => setMed(t('case.t_25'))}>{t('case.t_25')}</List.Item>
          <List.Item onClick={() => setMed(t('case.t_31'))}>{t('case.t_31')}</List.Item>
        </List>
      </Popup>
    </div>
  );
};

export default CaseMain;
